#include "head.h"

int makechild(processData_t *workerList,int childNum)
{
    pid_t pid;
    int pipeFd[2];

    for(int i=0;i<childNum;i++){
        socketpair(AF_LOCAL,SOCK_STREAM,0,pipeFd);//创建本地套接字 全双工管道
        pid=fork();
        ERROR_CHECK(pid,-1,"fork");
        if(pid==0){
            close(pipeFd[1]);
            handleEvent(pipeFd[0]);//子进程暂时循环
        }else{
            close(pipeFd[0]);
            workerList[i].pid=pid;
            workerList[i].status=FREE;
            workerList[i].pipeFd=pipeFd[1];
#ifdef DEBUG
            printf("worker[%d] pid=%d\n",i,pid);
            printf("workerList[%d].pipeFd=%d\n",i,pipeFd[1]);
#endif
        }
    }
    return 0;
}

int handleEvent(int pipeFd)
{
    int new_fd,finish_flag=0;
    while(1){
        //收到任务
        recvFd(pipeFd,&new_fd);
        finish_flag=0;
        printf("Worker recv task %d success!\n",new_fd);
        //给客户端发文件
        sleep(3);
        //通知父进程执行任务结束
        finish_flag=1;
        write(pipeFd,&finish_flag,sizeof(int));
        printf("Child finish task!\n");       
    }
}